<?php


namespace App\Http\Controllers\Admin\User;

use App\Exceptions\LogicException;
use App\Http\Controllers\Controller;
use App\Models\Adminer\Menus;
use App\Utils\ArrUtil;
use App\Utils\ResUtil;
use App\Models\Adminer\Admins;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Utils\GenerateCode;

class LoginController extends Controller
{

    public function login()
    {
        $data = request()->all();
        $rule = [
            'phone' => 'string|required',
            'password' => 'string|required'
        ];
        $validator = validatorService()->checkValidator($rule, $data, Admins::$fillables);
        if ($validator['code'] != 200) {
            throw new LogicException($validator['data']);
        }

        $user = Admins::getByMobile($data['phone']);
        if(!$user) {
            throw new LogicException('用户不存在，账号错误!');
        }
        if($user->password !== sha1((string) $data['password'])) {
            throw new LogicException('密码错误!');
        }
        if($user->enable == 0) {
            throw new LogicException('用户已被禁封!!');
        }

        $Authorization = GenerateCode::str(60) . md5((string) $user->id);
        $user_info = $user;
        $STID = $user->id;
        $user->tk = $Authorization;
        $user->save();
        return $this->ok(compact('STID', 'Authorization', 'user_info'));
    }

    public function logout(Admins $admin)
    {
        $adminer = $admin->currentAdminer();
        $adminer->tk = GenerateCode::str(60) . md5((string) $adminer->id);;
        $adminer->save();
        return $this->ok();
    }

    public function menus(Admins $admins)
    {
        $adminer = $admins->currentAdminer();
        if (($adminer->name ?? '') == 'admin') {
            $menus = Menus::getMenusByRoleId('', false, true);
        } else {
            $menus = Menus::getMenusByRoleId($adminer->role_id, false, true);
        }

        $routeListArr = [];
        foreach ($menus as $key => $item) {
            $routeListArr[] = ArrUtil::buildRouteNode($item);
        }
        $cachaMenuData = ArrUtil::buildRouteTree($routeListArr);
        return $this->ok(compact('cachaMenuData'));
    }
}
